// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    searchKeyword: '',
    hotProducts: [
      { name: 'X100' }, { name: 'Pro-7' }, { name: 'Air-Plus' }, { name: 'Sonic' }
    ],
    recentViewed: [
      { id: 1, title: 'A1 安装指南' },
      { id: 2, title: 'B2 快速上手' }
    ],
    // 产品数据（从说明书库复制）
    manuals: [
      {
        id: 1,
        title: 'Magic 6 Pro 使用手册',
        category: 'smartphone',
        version: 'v2.1',
        size: '12.5MB',
        pages: 156,
        downloadCount: 12580,
        lastUpdate: '2024-01-15',
        description: '荣耀Magic 6 Pro完整使用指南，包含功能介绍、操作技巧、故障排除等',
        tags: ['旗舰', '摄影', 'AI'],
        thumbnail: '📱'
      },
      {
        id: 2,
        title: 'MagicBook X 14 安装指南',
        category: 'laptop',
        version: 'v1.8',
        size: '8.2MB',
        pages: 89,
        downloadCount: 8930,
        lastUpdate: '2024-01-10',
        description: 'MagicBook X 14笔记本电脑开箱、安装、首次使用完整流程',
        tags: ['轻薄', '办公', '性能'],
        thumbnail: '💻'
      },
      {
        id: 3,
        title: 'MagicPad 13 快速上手',
        category: 'tablet',
        version: 'v1.5',
        size: '6.8MB',
        pages: 67,
        downloadCount: 5670,
        lastUpdate: '2024-01-08',
        description: 'MagicPad 13平板电脑快速入门指南，让您快速掌握核心功能',
        tags: ['大屏', '创作', '娱乐'],
        thumbnail: '📟'
      },
      {
        id: 4,
        title: 'Earbuds X5 配对教程',
        category: 'audio',
        version: 'v1.2',
        size: '3.5MB',
        pages: 34,
        downloadCount: 15200,
        lastUpdate: '2024-01-05',
        description: 'Earbuds X5真无线耳机配对、使用、维护完整教程',
        tags: ['无线', '降噪', '音质'],
        thumbnail: '🎧'
      },
      {
        id: 5,
        title: '智能手表 GT4 功能详解',
        category: 'smart',
        version: 'v2.0',
        size: '9.1MB',
        pages: 112,
        downloadCount: 7890,
        lastUpdate: '2024-01-12',
        description: '智能手表GT4所有功能详细说明，健康监测、运动模式、智能提醒等',
        tags: ['健康', '运动', '智能'],
        thumbnail: '⌚'
      },
      {
        id: 6,
        title: 'Magic Charger 使用说明',
        category: 'accessories',
        version: 'v1.0',
        size: '2.1MB',
        pages: 23,
        downloadCount: 4560,
        lastUpdate: '2024-01-03',
        description: 'Magic无线充电器使用说明，支持多种设备快速充电',
        tags: ['无线充电', '快充', '兼容'],
        thumbnail: '🔌'
      }
    ],
    filteredManuals: [],
    showSearchResults: false
  },
  // 搜索输入与确认
  handleSearchInput(e) { 
    this.setData({ searchKeyword: e.detail.value })
    // 实时搜索
    this.filterManuals()
  },
  handleSearchConfirm() {
    const keyword = (this.data.searchKeyword || '').trim()
    if (!keyword) {
      wx.showToast({ title: '请输入关键词', icon: 'none' })
      return
    }
    // 执行搜索并显示结果
    this.filterManuals()
  },

  // 过滤产品（与说明书库相同的搜索逻辑）
  filterManuals() {
    const { searchKeyword, manuals } = this.data
    let filtered = [...manuals]

    // 按关键词搜索
    if (searchKeyword.trim()) {
      const keyword = searchKeyword.toLowerCase()
      filtered = filtered.filter(manual => 
        manual.title.toLowerCase().includes(keyword) ||
        manual.description.toLowerCase().includes(keyword) ||
        manual.tags.some(tag => tag.toLowerCase().includes(keyword))
      )
    }

    this.setData({
      filteredManuals: filtered,
      showSearchResults: searchKeyword.trim().length > 0
    })
  },
  

  // 扫码、AI、AR、帮助
  handleScan() {
    if (!wx.scanCode) { wx.showToast({ title: '当前基础库不支持扫码', icon: 'none' }); return }
    wx.scanCode({
      onlyFromCamera: false,
      success: (res) => {
        const result = res.result || ''
        if (result) {
          wx.navigateTo({ url: '/pages/search/search?kw=' + encodeURIComponent(result) })
        }
      }
    })
  },

  // 跳转至 AI 助手页面
  goToAI() {
    wx.navigateTo({
      url: '/pages/ai/ai'
    })
  },

  // 跳转至 AR 指引页面
  goToAR() {
    wx.navigateTo({
      url: '/pages/ar/ar'
    })
  },

  // 语音输入（占位演示，实际可接入录音转写能力）
  handleVoiceInput() {
    wx.showToast({ title: '语音识别功能待接入', icon: 'none' })
  },

  // 卡片点击
  openHot() { 
    wx.switchTab({
      url: '/pages/category/category'
    })
  },
  openRecent() { 
    wx.switchTab({
      url: '/pages/category/category'
    })
  },
  openMyProducts() { 
    wx.navigateTo({
      url: '/pages/myProduct/myProduct'
    })
  },
  openAddProduct() { 
    console.log('openAddProduct called')
    wx.switchTab({
      url: '/pages/category/category',
      success: function() {
        console.log('Navigation to category page successful')
      },
      fail: function(err) {
        console.error('Navigation to category page failed:', err)
        wx.showToast({
          title: '页面跳转失败',
          icon: 'error'
        })
      }
    })
  },
  

  // 使用帮助
  goToHelp() {
    wx.navigateTo({
      url: '/pages/help/help'
    })
  },

  // 查看产品详情
  viewManual(e) {
    const manualId = e.currentTarget.dataset.id
    const manual = this.data.manuals.find(m => m.id === manualId)
    
    if (manual) {
      wx.showModal({
        title: manual.title,
        content: `版本：${manual.version}\n大小：${manual.size}\n页数：${manual.pages}\n下载量：${manual.downloadCount}\n\n${manual.description}`,
        confirmText: '查看详情',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            // 跳转到说明书库页面查看详情
            wx.switchTab({
              url: '/pages/category/category'
            })
          }
        }
      })
    }
  },

  // 添加到我的产品
  favoriteManual(e) {
    const manualId = e.currentTarget.dataset.id
    const manual = this.data.manuals.find(m => m.id === manualId)
    
    if (manual) {
      // 创建产品对象
      const newProduct = {
        id: Date.now(),
        title: manual.title,
        category: this.getCategoryName(manual.category),
        model: manual.title,
        purchaseDate: this.getCurrentDate(),
        warranty: this.getWarrantyDate(),
        status: 'active',
        isFavorite: true,
        lastViewed: this.getCurrentDate(),
        thumbnail: manual.thumbnail,
        description: manual.description,
        tags: manual.tags,
        serialNumber: this.generateSerialNumber(manual.title)
      }
      
      // 获取现有的我的产品列表
      let myProducts = []
      try {
        myProducts = wx.getStorageSync('myProducts') || []
      } catch (error) {
        console.error('获取我的产品失败:', error)
      }
      
      // 检查是否已存在相同产品
      const existingProduct = myProducts.find(p => p.title === manual.title)
      if (existingProduct) {
        wx.showToast({
          title: '产品已存在',
          icon: 'none'
        })
        return
      }
      
      // 添加新产品
      myProducts.push(newProduct)
      
      // 保存到本地存储
      try {
        wx.setStorageSync('myProducts', myProducts)
        wx.showToast({
          title: '添加成功',
          icon: 'success'
        })
      } catch (error) {
        console.error('保存产品失败:', error)
        wx.showToast({
          title: '添加失败',
          icon: 'error'
        })
      }
    }
  },

  // 获取分类名称
  getCategoryName(categoryId) {
    const categoryMap = {
      'smartphone': '智能手机',
      'laptop': '笔记本电脑',
      'tablet': '平板电脑',
      'audio': '音频设备',
      'smart': '智能设备',
      'accessories': '配件'
    }
    return categoryMap[categoryId] || '其他'
  },

  // 获取当前日期
  getCurrentDate() {
    const now = new Date()
    return `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`
  },

  // 获取保修期日期（当前日期+1年）
  getWarrantyDate() {
    const now = new Date()
    const warrantyDate = new Date(now.getFullYear() + 1, now.getMonth(), now.getDate())
    return `${warrantyDate.getFullYear()}-${(warrantyDate.getMonth() + 1).toString().padStart(2, '0')}-${warrantyDate.getDate().toString().padStart(2, '0')}`
  },

  // 生成序列号
  generateSerialNumber(title) {
    const prefix = title.replace(/\s+/g, '').substring(0, 6).toUpperCase()
    const timestamp = Date.now().toString().slice(-6)
    return `${prefix}${timestamp}`
  },

  // 显示测试选项
  showTestOptions() {
    const app = getApp()
    
    wx.showActionSheet({
      itemList: [
        '重置相机权限状态',
        '检查权限状态',
        '手动触发权限询问'
      ],
      success: (res) => {
        switch(res.tapIndex) {
          case 0:
            // 重置权限状态
            app.resetCameraPermissionStatus()
            wx.showToast({
              title: '权限状态已重置',
              icon: 'success'
            })
            break
          case 1:
            // 检查权限状态
            const status = app.getCameraPermissionStatus()
            const hasAsked = wx.getStorageSync('hasAskedCameraPermission')
            wx.showModal({
              title: '权限状态',
              content: `权限状态: ${status}\n已询问过: ${hasAsked ? '是' : '否'}`,
              showCancel: false
            })
            break
          case 2:
            // 手动触发权限询问
            app.checkCameraPermission()
            break
        }
      }
    })
  }
})
